//
//  PublicAccountDao.m
//  SouthChina
//
//  Created by creator_lq on 14/12/4.
//  Copyright (c) 2014年 科创. All rights reserved.
//

#import "PublicAccountDao.h"
#import "DataDict.h"
@implementation PublicAccountDao

/**
 *	@brief	更新所有应用列表
 *
 *	@param 	appList 应用列表数据
 *
 *	@return	return 成功标识
 */
+(BOOL)updataDBwithSQLiteStatement:(NSArray*)appList{

    
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    
    [self checkTableCreatedInDb:_dataBase];
    
    [_dataBase beginTransaction];
    
    BOOL isRollBack = NO;
    @try {
         NSString * delsql = [NSString stringWithFormat:@"DELETE from publicaccount "];
        [_dataBase executeUpdate:delsql];

        for (int i = 0; i<[appList  count]; i++) {
            
            NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithDictionary:[appList objectAtIndex:i]];
            NSString *appid= [map objectForKey:APPID];
            NSString *appname= [map objectForKey:APPNAME];
            NSString *type= [map objectForKey:APPTYPE];
            NSString *sort= [map objectForKey:SORT];
            NSString *qp= [map objectForKey:APPQP];
            NSString *initalword= [map objectForKey:INITIALWORD];
            NSString *funcdesc= [map objectForKey:FUNCDESC];
            NSString *heandimg= [map objectForKey:HEADIMG];
            NSString *subsrcibestatus= [map objectForKey:SUBSCRIBESTATUS];
            NSString *isrecomend= [map objectForKey:ISRECOMEND];
            NSString *isreceive= [map objectForKey:ISRECEIVE];
            NSString *disablechat= [map objectForKey:DISABLECHAT];
            NSDate *updatime= [[map objectForKey:UPDATE_TIME] dateFromString];

            NSString *isBanner =[map objectForKey:ISBANNER];
            NSString *isBasic =[map objectForKey:ISBASIC];
            NSString *isHome =[map objectForKey:ISHOME];
            NSString *appType = [map objectForKey:APPLABEL];
            NSString *userSort =  [map objectForKey:USERSORT];
           
            
            [map removeObjectForKey:APPID];
            [map removeObjectForKey:APPNAME];
            [map removeObjectForKey:APPTYPE];
            [map removeObjectForKey:SORT];
            [map removeObjectForKey:APPQP];
            [map removeObjectForKey:INITIALWORD];
            [map removeObjectForKey:FUNCDESC];
            [map removeObjectForKey:HEADIMG];
            [map removeObjectForKey:SUBSCRIBESTATUS];
            [map removeObjectForKey:ISRECOMEND];
            [map removeObjectForKey:ISRECEIVE];
            [map removeObjectForKey:DISABLECHAT];
            [map removeObjectForKey:UPDATE_TIME];
            
            [map removeObjectForKey:ISBANNER];
            [map removeObjectForKey:ISBASIC];
            [map removeObjectForKey:ISHOME];
            [map removeObjectForKey:APPLABEL];
            [map removeObjectForKey:USERSORT];


            NSString *otherinf = [map JSONString];
            
            NSString *sql = @"INSERT INTO publicaccount (appId,appName,type,sort,qp,initialWord,funcDesc,headImg,subscribeStatus,isRecommend,isReceive,disableChat,OTHER_INFO,UPDATE_TIME,isBasic,isBanner,appType,isHome,userSort) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            
            BOOL a =[_dataBase executeUpdate:sql,appid,appname,type,sort,qp,initalword,funcdesc,heandimg,subsrcibestatus,isrecomend,isreceive,disablechat,otherinf,updatime,isBasic,isBanner,appType,isHome,userSort];
            
            if(!a){
                NSLog(@"失败");
            }else{
//                NSLog(@"成功=%@",appname);
                
            }
            
        }
    }
    @catch (NSException *exception) {
        
        NSLog(@"插入失败--------: %@",exception);
        
        isRollBack = YES;
        [_dataBase rollback];
    }
    @finally {
        if (!isRollBack) {
            [_dataBase commit];
        }
    }
    
    [_dataBase close];
    
    return YES;

}

/**
 *	@brief	根据appid查询应用信息
 *
 *	@param 	appid 	<#appid description#>
 *
 *	@return	<#return value description#>
 */
+(PublicAccount*)queryForId:(NSString*)appid

{
    
    NSString * sql = @"SELECT * from publicaccount where appId=?";
    
 
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    FMResultSet *rs=[_dataBase executeQuery:sql,appid];
    PublicAccount *publicaccount = nil;
    while ([rs next]) {
        publicaccount = [[PublicAccount alloc] init];
        publicaccount.appId =[rs stringForColumn:APPID];
        publicaccount.appName =[rs stringForColumn:APPNAME];
        publicaccount.type =[rs stringForColumn:APPTYPE];
        publicaccount.sort =[rs stringForColumn:SORT];
        publicaccount.qp =[rs stringForColumn:APPQP];
        publicaccount.initialWord =[rs stringForColumn:INITIALWORD];
        publicaccount.funcDesc =[rs stringForColumn:FUNCDESC];
        publicaccount.headImg =[rs stringForColumn:HEADIMG];
        publicaccount.subscribeStatus =[rs stringForColumn:SUBSCRIBESTATUS];
        publicaccount.isRecommend =[rs stringForColumn:ISRECOMEND];
        publicaccount.isReceive =[rs stringForColumn:ISRECEIVE];
        publicaccount.disableChat =[rs stringForColumn:DISABLECHAT];
        publicaccount.otherInfo =[rs stringForColumn:OTHER_INFO];
        publicaccount.upate_time =[rs dateForColumn:UPDATE_TIME];
        
        publicaccount.isBanner =[rs stringForColumn:ISBANNER];
        publicaccount.isBasic =[rs stringForColumn:ISBASIC];
        publicaccount.isHome =[rs stringForColumn:ISHOME];
        publicaccount.appType = [rs stringForColumn:APPLABEL];
        publicaccount.userSort = [rs stringForColumn:USERSORT];
        break;
    };
    [rs close];
    [_dataBase close];
    return publicaccount;
}

/**
 *	@brief	查询订阅或者没订阅的APP
 *
 *	@param 	isSub 	1订阅 0未订阅
 *
 *	@return	<#return value description#>
 */
+(NSArray*)getSubscribePublicAccount:(BOOL)isSub
{
    
    NSMutableArray * applist = [[NSMutableArray alloc] init];
    NSString * sql = @"SELECT * from publicaccount where subscribeStatus=? order by APPID asc";
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    FMResultSet *rs=[_dataBase executeQuery:sql,isSub?@"1":@"0"];
    PublicAccount *publicaccount = nil;
    while ([rs next]) {
        publicaccount = [[PublicAccount alloc] init];
        publicaccount.appId =[rs stringForColumn:APPID];
        publicaccount.appName =[rs stringForColumn:APPNAME];
        publicaccount.type =[rs stringForColumn:APPTYPE];
        publicaccount.sort =[rs stringForColumn:SORT];
        publicaccount.qp =[rs stringForColumn:APPQP];
        publicaccount.initialWord =[rs stringForColumn:INITIALWORD];
        publicaccount.funcDesc =[rs stringForColumn:FUNCDESC];
        publicaccount.headImg =[rs stringForColumn:HEADIMG];
        publicaccount.subscribeStatus =[rs stringForColumn:SUBSCRIBESTATUS];
        publicaccount.isRecommend =[rs stringForColumn:ISRECOMEND];
        publicaccount.isReceive =[rs stringForColumn:ISRECEIVE];
        publicaccount.disableChat =[rs stringForColumn:DISABLECHAT];
        publicaccount.otherInfo =[rs stringForColumn:OTHER_INFO];
        publicaccount.upate_time =[rs dateForColumn:UPDATE_TIME];
        
        publicaccount.isBanner =[rs stringForColumn:ISBANNER];
        publicaccount.isBasic =[rs stringForColumn:ISBASIC];
        publicaccount.isHome =[rs stringForColumn:ISHOME];
        publicaccount.appType = [rs stringForColumn:APPLABEL];
        publicaccount.sort = [rs stringForColumn:USERSORT];
        [applist addObject:publicaccount];
    };
    [rs close];
    [_dataBase close];
    return applist;
    
}

/**
 *	@brief	查询主页APP信息
 *
 *
 *	@return	<#return value description#>
 */
+(NSArray*)getHomePublicAccount
{
    NSMutableArray * applist = [[NSMutableArray alloc] init];
    //20150814修改首页应用应该过滤掉isHome =0(isHome为已经删除的应用)
   // NSString * sql = @"SELECT * from publicaccount where subscribeStatus=1 ";
    NSString * sql = @"SELECT * from publicaccount where subscribeStatus=1  and isHome=1";
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    FMResultSet *rs=[_dataBase executeQuery:sql];
    PublicAccount *publicaccount = nil;
    while ([rs next]) {
        publicaccount = [[PublicAccount alloc] init];
        publicaccount.appId =[rs stringForColumn:APPID];
        publicaccount.appName =[rs stringForColumn:APPNAME];
        publicaccount.type =[rs stringForColumn:APPTYPE];
        publicaccount.sort =[rs stringForColumn:SORT];
        publicaccount.qp =[rs stringForColumn:APPQP];
        publicaccount.initialWord =[rs stringForColumn:INITIALWORD];
        publicaccount.funcDesc =[rs stringForColumn:FUNCDESC];
        publicaccount.headImg =[rs stringForColumn:HEADIMG];
        publicaccount.subscribeStatus =[rs stringForColumn:SUBSCRIBESTATUS];
        publicaccount.isRecommend =[rs stringForColumn:ISRECOMEND];
        publicaccount.isReceive =[rs stringForColumn:ISRECEIVE];
        publicaccount.disableChat =[rs stringForColumn:DISABLECHAT];
        publicaccount.otherInfo =[rs stringForColumn:OTHER_INFO];
        publicaccount.upate_time =[rs dateForColumn:UPDATE_TIME];
        
        publicaccount.isBanner =[rs stringForColumn:ISBANNER];
        publicaccount.isBasic =[rs stringForColumn:ISBASIC];
        publicaccount.isHome =[rs stringForColumn:ISHOME];
        publicaccount.appType = [rs stringForColumn:APPLABEL];
        publicaccount.userSort = [rs stringForColumn:USERSORT];
        [applist addObject:publicaccount];
    };
    [rs close];
    [_dataBase close];
    return applist;
    
}



/**
 *	@brief	根据条件查询数据，如果还传了分类信息，查询出来的结果是分类数据
 *          分类字典结构 [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"dictdataName",@"我的应用",@"dictdataValue",  @"1", @"dictdataOrder", nil]]
 *          传出去后，分类结果增加一个app的key，values对应的就是该分类的应用列表
 *	@param 	conditionSQL 	conditionSQL description
 *
 *	@return	<#return value description#>
 */
+(NSArray*)getPublicAccountWhere:(NSString *)conditionSQL appTyps:(NSArray*) appTyps

{
    NSMutableArray * applist = [[NSMutableArray alloc] init];
    NSString * sql =[NSString stringWithFormat:@"SELECT * from publicaccount %@",conditionSQL];
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    FMResultSet *rs=[_dataBase executeQuery:sql];
    PublicAccount *publicaccount = nil;
    while ([rs next]) {
        publicaccount = [[PublicAccount alloc] init];
        publicaccount.appId =[rs stringForColumn:APPID];
        publicaccount.appName =[rs stringForColumn:APPNAME];
        publicaccount.type =[rs stringForColumn:APPTYPE];
        publicaccount.sort =[rs stringForColumn:SORT];
        publicaccount.qp =[rs stringForColumn:APPQP];
        publicaccount.initialWord =[rs stringForColumn:INITIALWORD];
        publicaccount.funcDesc =[rs stringForColumn:FUNCDESC];
        publicaccount.headImg =[rs stringForColumn:HEADIMG];
        publicaccount.subscribeStatus =[rs stringForColumn:SUBSCRIBESTATUS];
        publicaccount.isRecommend =[rs stringForColumn:ISRECOMEND];
        publicaccount.isReceive =[rs stringForColumn:ISRECEIVE];
        publicaccount.disableChat =[rs stringForColumn:DISABLECHAT];
        publicaccount.otherInfo =[rs stringForColumn:OTHER_INFO];
        publicaccount.upate_time =[rs dateForColumn:UPDATE_TIME];
        
        publicaccount.isBanner =[rs stringForColumn:ISBANNER];
        publicaccount.isBasic =[rs stringForColumn:ISBASIC];
        publicaccount.isHome =[rs stringForColumn:ISHOME];
        publicaccount.appType = [rs stringForColumn:APPLABEL];
        publicaccount.userSort = [rs stringForColumn:USERSORT];
        [applist addObject:publicaccount];
    };
    [rs close];
    [_dataBase close];
    
    if(appTyps != nil)
    {
        NSMutableArray * applistType = [[NSMutableArray alloc] initWithArray:appTyps];
        [applistType enumerateObjectsUsingBlock:
         ^(id obj, NSUInteger index, BOOL  *stop){

             DataDict *type = (DataDict *)obj;
             
             NSPredicate *predicate = [NSPredicate predicateWithFormat:@"appType== %@", type.dictdataName ];
             NSArray * sAPP = [applist filteredArrayUsingPredicate:predicate];
             type.otheArray =  sAPP;
         }];
        return applistType;
    }
    else
    {
       return applist;
    }
    
}



/**
 *	@brief	根据应用名称的关键字查询应用
 *
 *	@param 	key 	<#key description#>
 *
 *	@return	<#return value description#>
 */
+(NSArray*)searcherNodePublicAccount:(NSString*)key
{
    NSString * sql = [NSString stringWithFormat:@"SELECT * from publicaccount where  appName  like '%%%@%%' or funcDesc like '%%%@%%' order by subscribeStatus desc,appname desc  ",key,key];
    NSMutableArray * applist = [[NSMutableArray alloc] init];
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    FMResultSet *rs=[_dataBase executeQuery:sql];
    PublicAccount *publicaccount = nil;
    while ([rs next]) {
        publicaccount = [[PublicAccount alloc] init];
        publicaccount.appId =[rs stringForColumn:APPID];
        publicaccount.appName =[rs stringForColumn:APPNAME];
        publicaccount.type =[rs stringForColumn:APPTYPE];
        publicaccount.sort =[rs stringForColumn:SORT];
        publicaccount.qp =[rs stringForColumn:APPQP];
        publicaccount.initialWord =[rs stringForColumn:INITIALWORD];
        publicaccount.funcDesc =[rs stringForColumn:FUNCDESC];
        publicaccount.headImg =[rs stringForColumn:HEADIMG];
        publicaccount.subscribeStatus =[rs stringForColumn:SUBSCRIBESTATUS];
        publicaccount.isRecommend =[rs stringForColumn:ISRECOMEND];
        publicaccount.isReceive =[rs stringForColumn:ISRECEIVE];
        publicaccount.disableChat =[rs stringForColumn:DISABLECHAT];
        publicaccount.otherInfo =[rs stringForColumn:OTHER_INFO];
        publicaccount.upate_time =[rs dateForColumn:UPDATE_TIME];
        
        publicaccount.isBanner =[rs stringForColumn:ISBANNER];
        publicaccount.isBasic =[rs stringForColumn:ISBASIC];
        publicaccount.isHome =[rs stringForColumn:ISHOME];
        publicaccount.appType = [rs stringForColumn:APPLABEL];
        publicaccount.userSort = [rs stringForColumn:USERSORT];
        
        [applist addObject:publicaccount];
    };
    [rs close];
    [_dataBase close];
    return applist;
    
}

/**
 *	@brief	跟新一个应用的信息
 *
 *	@param 	publicAccount 	<#publicAccount description#>
 *
 *	@return	<#return value description#>
 */
+(BOOL)updatePublicAccount:(PublicAccount*)publicAccount
{
    
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    
    [self checkTableCreatedInDb:_dataBase];
    
    [_dataBase beginTransaction];
    
    BOOL isRollBack = NO;
    BOOL a = YES;
    @try {
        
        NSString *sql = @"INSERT INTO publicaccount (appId,appName,type,sort,qp,initialWord,funcDesc,headImg,subscribeStatus,isRecommend,isReceive,disableChat,OTHER_INFO,UPDATE_TIME,isBasic,isBanner,appType,isHome,userSort) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        NSString * delsql = [NSString stringWithFormat:@"DELETE from publicaccount where appId='%@'",publicAccount.appId];
        
        [_dataBase executeUpdate:delsql];
        a =[_dataBase executeUpdate:sql,publicAccount.appId,publicAccount.appName,publicAccount.type,publicAccount.sort,publicAccount.qp,publicAccount.initialWord,publicAccount.funcDesc,publicAccount.headImg,publicAccount.subscribeStatus,publicAccount.isRecommend,publicAccount.isReceive,publicAccount.disableChat,publicAccount.otherInfo,publicAccount.upate_time,publicAccount.isBasic,publicAccount.isBanner,publicAccount.appType,publicAccount.isHome,publicAccount.userSort];

    }
    @catch (NSException *exception) {
        
        NSLog(@"插入失败--------: %@",exception);
        
        isRollBack = YES;
        [_dataBase rollback];
    }
    @finally {
        if (!isRollBack) {
            [_dataBase commit];
        }
    }
    [_dataBase close];
    return a;

  
}

/**
 *	@brief	添加一个应用
 *
 *	@param 	map 	<#map description#>
 *
 *	@return	<#return value description#>
 */
+(BOOL)insertPublicAccount:(NSDictionary*)map
{
    
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    
    [self checkTableCreatedInDb:_dataBase];
    
    [_dataBase beginTransaction];
    
    BOOL isRollBack = NO;
    BOOL a = YES;
    @try {
        
        NSString * delsql = [NSString stringWithFormat:@"DELETE from publicaccount where appId='%@'",[map objectForKey:@"appId"]];
        
        NSString *sql = @"INSERT INTO publicaccount (appId,appName,type,sort,qp,initialWord,funcDesc,headImg,subscribeStatus,isRecommend,isReceive,disableChat,OTHER_INFO,UPDATE_TIME,isBasic,isBanner,appType,isHome,userSort) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        
        [_dataBase executeUpdate:delsql];
        a =[_dataBase executeUpdate:sql,[map objectForKey:APPID],[map objectForKey:APPNAME],[map objectForKey:APPTYPE],[map objectForKey:SORT],[map objectForKey:APPQP],[map objectForKey:INITIALWORD],[map objectForKey:FUNCDESC],[map objectForKey:HEADIMG],[map objectForKey:SUBSCRIBESTATUS],[map objectForKey:ISRECOMEND],[map objectForKey:ISRECEIVE],[map objectForKey:DISABLECHAT],nil,[NSDate date],[map objectForKey:ISBASIC],[map objectForKey:ISBANNER],[map objectForKey:APPLABEL],[map objectForKey:ISHOME],[map objectForKey:USERSORT]];
        
    }
    @catch (NSException *exception) {
        
        NSLog(@"插入失败--------: %@",exception);
        
        isRollBack = YES;
        [_dataBase rollback];
    }
    @finally {
        if (!isRollBack) {
            [_dataBase commit];
        }
    }
    [_dataBase close];
    return a;

    
}

/**
 *	@brief	创建应用本地数据库
 *
 *	@param 	db 	<#db description#>
 *
 *	@return	<#return value description#>
 */
+(BOOL)checkTableCreatedInDb:(FMDatabase *)db
{
    NSString *createStr=@"CREATE  TABLE  IF NOT EXISTS 'publicaccount' ('appId' text PRIMARY KEY  NOT NULL  UNIQUE ,'appName' text,'type' text, 'sort' text,'qp' text,'initialWord' text,'funcDesc' text,'headImg' text,'subscribeStatus' text,'isRecommend' text,'isReceive' text,'disableChat' text,'OTHER_INFO' text,'UPDATE_TIME' date,'isBasic' text,'isBanner' text,'appType' text,'isHome' text,'userSort' text)";
    
    BOOL worked = [db executeUpdate:createStr];
    FMDBQuickCheck(worked);
    return worked;
}


@end
